//
//  QAuthViewController.swift
//  Weibo
//
//  Created by 孙成宇 on 15/11/27.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit

import AFNetworking




class OAuthViewController: UIViewController {

    
   
    let webView = UIWebView()
    
    
    @objc private func close(){
    
  
    dismissViewControllerAnimated(true, completion: nil)
        
    
    
    }
    @objc private func defaultAccount() {
        
        //本地代码 和js通讯
        let jsString = "document.getElementById('userId').value = '18581661692', document.getElementById('passwd').value = 'sunny990...' "
        webView.stringByEvaluatingJavaScriptFromString(jsString)
        
    }

    
    
    
    
    
    override func loadView() {
        view = webView
       webView.delegate = self
    
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //设置导航条
        
         navigationItem.leftBarButtonItem = UIBarButtonItem(title:"关闭", style: .Plain ,target: self , action: "close")
        
       
        
        //上线前 记得注销
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "defaultAccount")
        
        
        
        
        
        
        loadOauthPage()

        
    }
    
    //MARK 加载授权界面
    private func loadOauthPage(){
    
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        
        if let url = NSURL(string: urlString){
        
        let request = NSURLRequest(URL: url)
        
        webView.loadRequest(request)
       
    
        }
    
    
    }
    
    
}
    
    
      extension OAuthViewController: UIWebViewDelegate  {
        func webViewDIdFinisheLoad(webView : UIWebView) {
        
          SVProgressHUD.dismiss()
        
        
        }
        func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
        
        }
    
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
       // print(request)
        let urlString = request.URL?.absoluteString ?? ""
     

    //屏蔽掉不希望加载的页面
    if urlString.hasPrefix("https://api.weibo.com/") {
       return true
    }
    
    if !urlString.hasPrefix("http://www.itcast.cn") {
      return false
    }
    
    
    //程序如果走到这里  就只有包含回调的url才能运行到此
    //获取授权码
        guard let query = request.URL?.query else{
        return false
            }
        let  codeStr = "code="
        let code = query.substringFromIndex(codeStr.endIndex)
        
    // print(query)
    // print(code)
        //获取code码
        //请求用户toKen
        userAccountViewModel().loadAccesssToken(code) { (error) -> () in
            
            
            if error != nil{
            
            
                SVProgressHUD.showErrorWithStatus("你的网络正在睡觉,请稍后")
                return
            
            }
            
            self.dismissViewControllerAnimated(false) { () -> Void in

                NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootVCNotification, object: nil)
        }


        }
        
        
        
        
       // SVProgressHUD.showSuccessWithStatus("登录成功")
        
    return false

    }
        
       
}
